<?php
/**
 * Manages rules for an item
 * 
 */
class NewsController extends Controller {

   
    /*
     * Browse for items
     */
    public function browse(){

    }
    
    /*
     * Show a single item
     */

    //Show a category and list the news in that category under "Klimatnyheter" in the left bar.
    public function listNews(/*$id*/)
    {

        $search = isset($_GET['search'])? mres($_GET['search']) : '';
        $id = $this->query[2];
        //$id = isset($_GET['id'])? mres($_GET['id']): 0;

        $latestId = 0;
        if (is_numeric($id) && $id > 0) {
                $latest= $this->model->getNews($id);
                $this->set('latest', $latest);
                $latestId = $latest[0]['id'];
                if (!isset($_SESSION['visited_news'][$id])) {

                    //funkar
                    $this->model->IncreaseViews($id);
                    $_SESSION['visited_news'][$id]=true;
                }
        }

        $category = $this->query[0];
        if ($this->query[1])
        {
            $sub = $this->query[1];
        }
        else
        {
            $sub = "00";
        }

        //Ta bort om vi flyttar if-satser i fourth!
        $this->set('sub', $sub);
        $this->set('category', $category);
        //Hämtar 'cat' FROM 'klimat_prod_cat' där nummer = "$category"."$sub"
        $catname=$this->model->getCat($category, $sub);

        $this->set('catname', $catname);

        if ($category>0) {
            $low = $category."00";
            $high = ($category+1)."00";
            $this->set('low', $low);
            $this->set('high', $high);
            //istället för if (isset($_GET['sub']))
            if (isset($sub) && $sub <> 00)
            {
                //Hämtar news_id från news_group som är hidden och har 'group_id' = '$category'.'$sub'
                $getcatnews = $this->model->getCatNewsID($category, $sub);
            }
            else    //Hämtar news_id från news_group som är hidden och har 'group_id' mellan '$low' och '$high'
            {
                    $getcatnews = $this->model->getCatNewsLH($low,$high);
            }
            $length = count($getcatnews);
            for ($i=0; $i<=$length-1; $i++)
            {
                $categories = $categories . $getcatnews[$i]['news_id'];
                if ($i != $length-1) //om det är sista värdet i $getcategories ska det inte vara någon ", " i slutet
                $categories .= ", ";
            }

            if (isset($categories)) {
                    $catsql = "1";
            }
        }
        if (!isset($catsql) && $category>0)
                $catsql = "2";
        elseif (!isset($catsql))
                $catsql = "3";


        if ($search)
        {
            //$getnews=mysql_query("SELECT `id`, `title`, `text`, `text2`, `mainlink`, `mainlink_activated`, `date_publish`, `date_publish2`, `date_publish3`, `date_publish4`, `user_id`, `text_source`, `text_source_activated`, `img_source`, `img_file`, `img_description` FROM `news` WHERE $catsql NOW() BETWEEN `date_publish` AND `date_end` AND `approved`='1' AND `deleted`='0' AND (`title` LIKE '%$search%' OR `text` LIKE '%$search%' OR `text2` LIKE '%$search' OR `img_description` LIKE '%$search%') ORDER BY `date_publish` DESC, `id` DESC");
            $searchMethod = 'like'; //'match'
            if($searchMethod == 'like')
            {
                $getnews = $this->model->getNewsFromCat($catsql, $categories, $search);


            }
                else //'match', the table must be myisam on MySQL 4.1...
                {
                    $getnews = $this->model->getNewsFromCat2($catsql, $categories, $search);
                }
        }
        else
        {
            // Fixad medhj�lp av en �vanst�ende fr�ga f�r att f� ut alla nyheter i en kategori
            $getnews = $this->model->getNewsFromCat3($catsql, $categories);
        }



        if (count($getnews) == 0)
                $nonews = true;
        else
                $nonews = false;
        $this->set('nonews, $nonews');

        if (!$nonews && $catsql<>"3" || !$category)
            {

                //mycket mysko.... FIXME

                $latestSet = false;
                //fixa denna loop
                $length = count($getnews);
                $gn = $getnews;

                for ($i=0; $i<=$length-1; $i++)
                {
                    $catresult = $this->model->getNewsGroup($gn[$i]['id']);
                    if(count($catresult)==0){ $catresult = null; continue; }

                    if( $gn[$i]['date_publishx'] >= date("Y-m-d H:i:s") ) continue;
                    if (isset($duplicates) && isset($duplicates[$gn[$i]['id']])) continue;
                    $duplicates[$gn[$i]['id']]=true;
                    if (++$i > 60) { $limitreached=true; break; }
                    if( !$latestSet && $id==0 ) {
                            $latestId = $gn[$i]['id'];
                            $latestSet = true;
                            $latest = $gn[$i];
                    }
                    $text = strip_tags($gn[$i]['text'])." ".strip_tags($gn[$i]['text2']);
                    $title[] = substr($gn[$i]['title'],0,40);
                    $lentitle = strlen(strip_tags(substr($gn[$i]['title'],0,40)));



                    if (strlen($text) + $lentitle > 70) $text = substr($text,0,(70 - $lentitle));

                    $texten[] = $text;
                    $date_publishx[] = substr($gn[$i]['date_publishx'],0,10);
                    $newsID[] = $gn[$i]['id'];

                    //if ($i<=$length-1)
                    //{
                    $this->set('limitreached', $limitreached);
                    $this->set('date_publishx', $date_publishx);
                    //$this->set('$date_publishx[]', $date_publishx[]);
                    $this->set('text', $texten);
                    $this->set('title', $title);
                    $this->set('newsID', $newsID);
                    if (is_numeric($this->query[0]))
                    {
                        $query0 = $this->query[0];
                    }
                    if (is_numeric($this->query[1]))
                    {
                        $query1 = $this->query[1];
                    }
                    else
                    {
                        $query1 = "00";
                    }
                    if (is_numeric($this->query[2]))
                    {
                        $query2 = $this->query[2];
                    }
                    $this->set('query0', $query0);
                    $this->set('query1', $query1);
                    $this->set('query2', $query2);
                    //}
                }



        }
        else {
                $nonews=true;
                if (!$search) $ingaNyheter = "Inga nyheter i denna kategorien.";
                $this->set('ingaNyheter', $ingaNyheter);
        }
        if ($nonews && $search) {
            $searchFail = "S&ouml;kningen gav inga svar";
            $this->set('searchFail', $searchFail);
        }
        if (isset($limitreached) && $limitreached && !$nonews && !$search)
        {
            $needLink = true;
            $this->set('needLink', $needLink);
        }




    }



    public function third()
    {
        $getcategories = $this->model->getCatNum();
        $this->set('getcategories', $getcategories);
    }

    //fourth
    public function listSubCats()
    {       
        $category = $this->query[0];
        $getcats = $this->model->getSubCats($category);
        $this->set('getcats', $getcats);

    }

    public function fifth()
    {
    }

public function show(/*$id*/)
    {
        $this->listNews();
        //expandNews ska sitta i en if..? Och ha inparametrar.
        $this->showCompanyAdds();
        $this->third();
        $this->listSubCats();
       // $this->expand();
    }
//Show the adds from a certain category with text and loggo. The add allso links to the companys hompage.
    public function showCompanyAdds(/*$id*/)
    { // include/functions/products.php
	global $server, $serverUsed;
	$search_string	= isset($_POST['search'])? $_POST['search']:'';
	$result		= $this->model->getNumCat();
	$num_rows	= count($result);


        $length = count($result);
        for ($i=0; $i<=$length-1; $i++)
        {
            $cat[$i]['number']	= $result[$i]['number'];
            $cat[$i]['cat'] = $result[$i]['cat'];
        }   
        //Controll för $cat
        //$this->set('cat', $cat);

        if (is_numeric($this->query[2]))
        {
            $id = $this->query[2];
            $getcategories = $this->model->getGroupID($id);
            $this->set('getcategories', $getcategories);

            $length = count($getcategories);
            for ($i=0; $i<=$length-1; $i++)
            {
                $categories = $categories . $getcategories[$i][no];
                if ($i != $length-1) //om det är sista värdet i $getcategories ska det inte vara någon ", " i slutet
                $categories .= ", ";
            }        
        }
        elseif (is_numeric($this->query[0]) && is_numeric($this->query[1]) && $this->query[1]<>"00")
        {
            $categories = $this->query[0] . $this->query[1];            
        }
        else
        {
            if (is_numeric($this->query[0]))
            {
                $categories = $this->query[0];
                $catLow = $categories."00";
                $catHigh = ($categories+1)."00";
            }
        }
        $this->set('categories', $categories);

        if (isset($categories))
        {
            if($catLow <> $catHigh)
            {
                $result = $this->model->getAddLH($catLow, $catHigh);
            }
            else
            {
                $result = $this->model->getAdd($categories);           
            }
            $list = true;
            $this->set('result', $result);
            $this->set('list', $list);
        }
  }

  public function expand()
  {
      $category = $this->query[0];
      $sub = $this->query[1];

      		if ($category) {
			$low = $category."00";
			$high = ($category+1)."00";
			if ($sub) $getcatnews = $this->model->getCatNews($category,$sub);
			else $getcatnews = $this->model->getCatNews2($low,$high);
			while ($gcn = mysqli_fetch_assoc($getcatnews)) {
				$buffer[] = $gcn['news_id'];
			}
			if ($buffer) {
				$categories = implode(",",$buffer);
				$buffer=null;
				$catsql = "`id` IN($categories) AND";
			}
			else die("Inga nyheter hittades"); //inga nyheter hittades
		}
		$get= $this->model->getGet($catsql);
		while ($gn = mysqli_fetch_assoc($get)) {
			while ($gn = mysqli_fetch_assoc($get)) {
					if (!$latest) $latest = $gn;
					$date1 = $gn['date_publish'];
					$date2 = $gn['date_publish2'];
					$date3 = $gn['date_publish3'];
					$date4 = $gn['date_publish4'];
					if ($date1 > "0000-00-00 00:00:00") $news[$date1][]=$gn;
					if ($date2 > "0000-00-00 00:00:00") $news[$date2][]=$gn;
					if ($date3 > "0000-00-00 00:00:00") $news[$date3][]=$gn;
					if ($date4 > "0000-00-00 00:00:00") $news[$date4][]=$gn;

				}
				$i=0;
				krsort($news);
				foreach ($news as $date=>$n) {
					if ($date >= date("Y-m-d H:i:s")) continue;
					foreach ($n as $gn) {
						if (++$i > ($offset * 60)) { $limitreached=true; break; }
						$text = strip_tags($gn['text'])." ".strip_tags($gn['text2']);
						$title = substr($gn['title'],0,40);
						$lentitle = strlen(strip_tags($title));

						if (strlen($text) + $lentitle > 70) $text = substr($text,0,(70 - $lentitle));

						echo "<div style=\"padding:4px\"><small>".substr($gn['date_publish'],0,10)."</small><br/><a href=\"?page=news";
						if ($category) echo "&cat=$category";
						if ($_GET['sub']) echo "&sub=$sub";
						echo "&id=$gn[id]\"><b>".strip_tags($title)."</b>. $text &gt;&gt;</a></div>";
					}
				}
		}
		if ($limitreached) echo "<br/>
			<div style=\"text-align:right\" id=\"expander\"><a href=\"javascript:expand_news(", $offset+1,");\">Fler nyheter &gt;&gt;</a></div>";

  }


    }
?>
